package hc.bre.call

import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.jdbc.core.JdbcTemplate
import hc.bre.cmn.RuleDefinition
import hc.bre.cmn.RuleScriptBuilder
import java.util.concurrent.CompletableFuture

@groovy.transform.CompileStatic
class SqlQueryBuilder extends RuleScriptBuilder<SqlQueryDefinition>{
	@Override
	public void buildClassRuleBodyCore() {
		apdNl("//before query as below");
		apdNlBlock("${ruleDef.beforeQuery?:''}");

		apdNl("//execute sql query");
		buildSqlQuery();

		apdNl("//after sql query execution");
		apdNlBlock("${ruleDef.afterQuery?:''}");
	}

	public void buildSqlQuery() {
		ruleDef.list.each { SqlQueryItem sqlItem ->
			apdNl("String _${sqlItem.code}_statement_ = ").apd('"""')
			apdNlBlock(sqlItem.content).apdNl('""";');
		};

		apdNl();
		apdNl("${result}.data = new Object(){");

		nested {
			String CompletableFuture = className(CompletableFuture.class);
			String JdbcTemplate = className(JdbcTemplate.class);
			
			ruleDef.list.each { SqlQueryItem sqlItem ->
				apdNl();
				apdNl("${CompletableFuture}<List<Map<String, Object>>> ${sqlItem.code} =");
				apdNl("\t ${CompletableFuture}.supplyAsync({return (new ${JdbcTemplate}(${_dataSource()})).queryForList(_${sqlItem.code}_statement_)});");
				apdNl("List<Map<String, Object>> get${sqlItem.codeAsGetSetter()}(){return ${sqlItem.code}.get();};");
			};
		}
		apdNl("};");

	}
	
	String _dataSource()
	{
		return this.routeOfRuleItem(this.ruleOfSetting, ruleDef.dataSource)
	}
}
